package com.xneure.utils.bean;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import com.xneure.utils.ObjectUtil;

/**
 * bean属性处理工具 要求属性有 get set is 方法
 */
public class ClassProperty{
	private Field field;
	private PropertyDescriptor pd;

	public ClassProperty(Field field,Class<?> beanClass){
		this.field = field;
		loadProperty(field.getName(),beanClass);
	}

	private void loadProperty(String name,Class<?> beanClass){
		try{
			Map<String,String> methods = BeanProcessor.methods.get(beanClass);
			char[] chars = name.toCharArray();
			chars[0] = Character.toUpperCase(chars[0]);
			String readMethodName = methods.get("get".concat(name).toLowerCase());
			String writeMethodName = methods.get("set".concat(name).toLowerCase());
			if(null == writeMethodName){
				writeMethodName = methods.get("is".concat(name).toLowerCase());
				if(null == writeMethodName){
					writeMethodName = methods.get("add".concat(name).toLowerCase());
				}
			}
			pd = new PropertyDescriptor(name,beanClass,readMethodName,writeMethodName);
		}catch(Exception e){
		}
	}

	public Field getField(){
		return field;
	}

	public void setValue(Object obj,Object val){
		if(pd == null){
			ObjectUtil.modifyFieldValue(obj,field,val);
		}else{
			try{
				pd.getWriteMethod().invoke(obj,val);
			}catch(Exception e){
			}
		}
	}

	public Object getValue(Object obj){
		if(pd == null){
			return ObjectUtil.getFieldValue(obj,field);
		}else{
			try{
				return pd.getReadMethod().invoke(obj);
			}catch(Exception e){
				return null;
			}
		}
	}

	public Method getReadMethod(){
		return pd.getReadMethod();
	}

	public Method getWriteMethod(){
		return pd.getWriteMethod();
	}

	public Class<?> getType(){
		return pd.getPropertyType();
	}
}
